<template>
    <div>
        <el-button @click="openDialog('add')">新增开设课程</el-button>
        <el-dialog v-model="dialogVisible" :title="dialogTitle">
            <el-form :model="currentCourse" label-width="120px">
                <el-form-item label="课程名称">
                    <el-select v-model="currentCourse.courseId" placeholder="请选择课程名称" filterable>
                        <el-option
                            v-for="course in filteredCourses"
                            :key="course.courseId"
                            :label="course.courseName"
                            :value="course.courseId"
                        ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="教师">
                    <el-select v-model="currentCourse.staffNumber" placeholder="请选择教师" filterable>
                        <el-option
                            v-for="teacher in filteredTeachers"
                            :key="teacher.staffNumber" 
                            :label="teacher.name+' ('+teacher.staffNumber+')'"
                            :value="teacher.staffNumber"                             
                        ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="备注">
                    <el-input v-model="currentCourse.remark"></el-input>
                </el-form-item>
                <el-form-item label="课程容量">
                    <el-input v-model.number="currentCourse.capacity" type="number"></el-input>
                </el-form-item>
                <template v-if="hasScheduleInfo">
                    <div class="calendar-and-delete">
                        <div v-for="(schedule, index) in currentCourse.scheduleInfo" :key="index">
                            <template v-if="!schedule.isEditing">
                                <span style="display: inline-flex; align-items: center;">
                                    <p>{{ formatDateTime(schedule.startTime) }} - {{ formatDateTime(schedule.endTime) }} {{ schedule.room }}</p>
                                    <el-icon @click="editSchedule(index)" style="margin-left: 8px; cursor: pointer;">
                                        <EditPen />
                                    </el-icon>
                                </span>
                            </template>
                            <template v-else>
                                <el-form :model="schedule" label-width="80px">
                                    <el-form-item label="开始时间">
                                        <el-date-picker
                                            v-model="schedule.startTime"
                                            type="datetime"
                                            placeholder="请选择开始日期及时间"
                                            :picker-options="pickerOptions"
                                            @change="(value) => handleDateChange(value,'startTime', index)"
                                        />
                                    </el-form-item>
                                    <el-form-item label="结束时间">
                                        <el-date-picker
                                            v-model="schedule.endTime"
                                            type="datetime"
                                            placeholder="请选择结束日期及时间"
                                            :picker-options="pickerOptions"
                                            @change="(value) => handleDateChange(value, 'endTime', index)"
                                        />
                                    </el-form-item>
                                    <el-form-item label="教室">
                                        <el-input v-model="schedule.room"></el-input>
                                    </el-form-item>
                                    <el-button @click="saveSchedule(index)">保存</el-button>
                                    <el-button @click="cancelEdit(index)">取消</el-button>
                                </el-form>
                            </template>
                        </div>
                        <el-button 
                            v-if="showPreview" 
                            type="danger" 
                            @click="removeAllSchedules" 
                            style="margin-top: 10px;"
                        >删除所有日历安排</el-button>
                    </div>
                </template>
                <template v-else>
                    <el-button @click="addCourseDate">添加课程日期</el-button>
                    <template v-for="(dateInfo, index) in courseDates" :key="index">
                        <div class="course-date-section" :class="{ 'has-top-border': index > 0 }">
                            <div class="delete-button-wrapper">
                                <el-button 
                                    type="danger" 
                                    @click="removeCourseDate(index)" 
                                    :disabled="index === 0"
                                >删除</el-button>
                            </div>
                            <el-form-item :label="'日期'+ (index + 1)">
                                <el-date-picker
                                    v-model="dateInfo.startDate"
                                    type="date"
                                    placeholder="请选择开始日期及星期"
                                    :picker-options="pickerOptions"
                                    @change="(value) => updateCourseDateField(value, 'startDate', index)"
                                />
                            </el-form-item>
                            <el-form-item :label="'重复间隔'+ (index + 1)">
                                <el-select v-model="dateInfo.repeatInterval" placeholder="请选择重复间隔">
                                    <el-option label="每一周" value="7"></el-option>
                                    <el-option label="每两周" value="14"></el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item :label="'上课时段'+ (index + 1)">
                                <el-slider
                                    v-model="dateInfo.selectedPeriod"
                                    range
                                    :min="1"
                                    :max="10"
                                    @change="onSliderChange(index)"
                                    @input="onSliderInput(index)"
                                ></el-slider>
                                <span v-if="dateInfo.selectedPeriod.length === 2">
                                    已选中第 {{ dateInfo.selectedPeriod[0] }} - {{ dateInfo.selectedPeriod[1] }} 节
                                </span>
                            </el-form-item>
                            <el-form-item :label="'课时'+ (index + 1)">
                                <el-input v-model="dateInfo.repeatCount" placeholder="一共重复多少次" type="number" />
                            </el-form-item>
                            <el-form-item :label="'教室'+ (index + 1)">
                                <el-input v-model="dateInfo.classroom" @input="(value) => updateCourseDateField(value, 'classroom', index)"></el-input>
                            </el-form-item>
                        </div>
                    </template>
                </template>
            </el-form>
            <template #footer>
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleSubmit">{{ dialogButtonText }}</el-button>
                <el-button v-if="dialogMode === 'operate'" type="danger" @click="cancelCourseOffer">取消开课并删除</el-button>
            </template>
        </el-dialog>
        <el-table :data="courseStore.courseSchedules" stripe>
            <el-table-column prop="course.courseName" label="课程名称"></el-table-column>
            <el-table-column prop="teacher.name" label="教师"></el-table-column>
            <el-table-column prop="enrolledStudents" label="已选学生"></el-table-column>
            <el-table-column prop="capacity" label="课程容量"></el-table-column>
            <el-table-column label="操作">
                <template #default="scope">
                    <el-button @click="openDialog('operate', scope.row)">操作</el-button>
                </template>
            </el-table-column>
        </el-table>
    </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useCourseStore } from '@/stores/course';
import { useTeacherStore } from '@/stores/teacher'; 
import { EditPen } from '@element-plus/icons-vue';

const dialogVisible = ref(false);
const dialogMode = ref('');
const dialogTitle = ref('');
const dialogButtonText = ref('');
const currentCourse = ref({
    id: -1,
    courseId: '',
    staffNumber: '', 
    name: '',
    remark: '',
    capacity: 30,
    scheduleInfo: []
});
const showPreview = ref(false); 
const courseDates = ref([{ 
    startDate: '', 
    repeatInterval: '7', 
    selectedPeriod: [1, 1], 
    repeatCount: 0, 
    classroom: '' 
}]);
const hasScheduleInfo = computed(() => {
    if (dialogMode.value === 'operate') {
        const course = courseStore.courseSchedules.find(c => c.id === currentCourse.value.id);
        return course && course.scheduleInfo && course.scheduleInfo.length > 0;
    }
    return courseDates.value.some(dateInfo => dateInfo.repeatCount > 0);
});

const courseStore = useCourseStore();
const teacherStore = useTeacherStore();

const pickerOptions = {
    shortcuts: false,
    format: 'yyyy-MM-dd HH:mm:ss'
};

const classTimeRanges = [
    { start: '08:00', end: '08:45' },
    { start: '08:55', end: '09:40' },
    { start: '10:00', end: '10:45' },
    { start: '10:55', end: '11:40' },
    { start: '13:30', end: '14:15' },
    { start: '14:25', end: '15:10' },
    { start: '15:30', end: '16:15' },
    { start: '16:25', end: '17:10' },
    { start: '17:30', end: '18:15' },
    { start: '18:25', end: '19:10' }
];

const filteredCourses = computed(() => {
    if (!currentCourse.value.name) {
        return courseStore.courses;
    }
    return courseStore.courses.filter(course =>
        course.name.toLowerCase().includes(currentCourse.value.name.toLowerCase())
    );
});

const filteredTeachers = computed(() => {
    if (!currentCourse.value.teacherId) { 
        return teacherStore.teachers;
    }
    return teacherStore.teachers.filter(teacher =>
        teacher.staffNumber === currentCourse.value.teacherId 
    );
});

const openDialog = (mode, course = null) => {
    dialogMode.value = mode;
    if (mode === 'add') {
        dialogTitle.value = '新增课程';
        dialogButtonText.value = '确定';
        currentCourse.value = {
            id: -1,
            courseId: '',
            staffNumber: '',
            name: '',
            remark: '',
            capacity: 30,
            scheduleInfo: []
        };
        courseDates.value = [{ 
            startDate: '', 
            repeatInterval: '7', 
            selectedPeriod: [1, 1], 
            repeatCount: 0, 
            classroom: '' 
        }];
    } else if (mode === 'operate') {
        dialogTitle.value = '课程操作';
        dialogButtonText.value = '确认开课';
        currentCourse.value = {
            id: course.id,
            courseId: course.courseId,
            staffNumber: course.staffNumber,
            scheduleInfo: course.scheduleInfo,
            name: course.name,
            remark: course.remark,
            capacity: course.capacity,
        };
        if (course.scheduleInfo && course.scheduleInfo.length > 0) {
            showPreview.value = true;
        } else {
            showPreview.value = false;
        }
    }
    dialogVisible.value = true;
};

const onSliderInput = (index) => {
    const value = courseDates.value[index].selectedPeriod;
    const tempPeriod = ref(value);
    tempPeriod.value = value;
};

const onSliderChange = (index) => {
    const startIndex = courseDates.value[index].selectedPeriod[0] - 1;
    const endIndex = courseDates.value[index].selectedPeriod[1] - 1;
    courseDates.value[index].startTime = classTimeRanges[startIndex].start;
    courseDates.value[index].endTime = classTimeRanges[endIndex].end;
};

const formatDateTime = (timestamp) => {
    const date = new Date(timestamp);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    return `${year}年${month}月${day}日 ${hours}:${minutes}`;
};

const addCourseDate = () => {
    courseDates.value.push({ 
        startDate: '', 
        repeatInterval: '7', 
        selectedPeriod: [1, 1], 
        repeatCount: 0, 
        classroom: '' 
    });
};

const removeCourseDate = (index) => {
    if (index >= 0 && index < courseDates.value.length) {
        courseDates.value.splice(index, 1);
    }
};

const removeAllSchedules = () => {
    courseDates.value = [{ 
        startDate: '', 
        repeatInterval: '7', 
        selectedPeriod: [1, 1], 
        repeatCount: 0, 
        classroom: '' 
    }];
    showPreview.value = false;
    currentCourse.value.scheduleInfo = [];
};

const handleSubmit = async () => { 
    if (dialogMode.value === 'add') {
        const { courseId, staffNumber, capacity, remark } = currentCourse.value;
        const scheduleInfo = generateSchedule();
        
        const params = {
            courseId,
            staffNumber,
            capacity,
            remark,
            scheduleInfo
        };
        try {
            await courseStore.addCourseSchedule(params); 
            showNotification("课程开设成功", false);
        } catch (error) {
            showNotification("课程开设失败", true);
        }
    } else if (dialogMode.value === 'operate') {
        const { id, courseId, staffNumber, capacity, remark, scheduleInfo } = currentCourse.value;
        
        let finalScheduleInfo = []
        if (scheduleInfo === null) {
            finalScheduleInfo =  generateSchedule()                  
        }else{
            finalScheduleInfo = scheduleInfo
        }
        console.log(finalScheduleInfo)
        const params = {
            id,
            courseId,
            staffNumber,
            capacity,
            remark,
            scheduleInfo: finalScheduleInfo
        };
        if (params.scheduleInfo.length === 0) {
            //await courseStore.addCourseSchedule(params);
        } else {
            await courseStore.confirmCourseSchedule(params);
        }
        showNotification("操作成功", false);
    }
    dialogVisible.value = false;
};

const cancelCourseOffer = () => {
    if (dialogMode.value === 'operate') {
        courseStore.removeCourseSchedule(currentCourse.value.id)
        dialogVisible.value = false;
    }
};

const editSchedule = (index) => {
    currentCourse.value.scheduleInfo[index].isEditing = true;
};

const saveSchedule = (index) => {
    currentCourse.value.scheduleInfo[index].isEditing = false;
};

const cancelEdit = (index) => {
    currentCourse.value.scheduleInfo[index].isEditing = false;
};

const generateSchedule = () => {
    const schedules = [];
    let idCounter = 0;
    courseDates.value.forEach((dateInfo) => {
        const { startDate, repeatInterval, selectedPeriod, repeatCount, classroom } = dateInfo;
        const startIndex = selectedPeriod[0] - 1; // 假设 selectedPeriod 是从 1 开始的索引
        const endIndex = selectedPeriod[1] - 1;

        // 从 classTimeRanges 获取 startTime 和 endTime
        const startTimeStr = classTimeRanges[startIndex].start;
        const endTimeStr = classTimeRanges[endIndex].end;
        for (let i = 0; i < repeatCount; i++) {
            // 计算课程的开始时间（基于日期 + 时间）
            const courseDate = new Date(startDate);
            courseDate.setDate(courseDate.getDate() + i * parseInt(repeatInterval));

            // 生成课程的开始和结束时间
            const scheduleStartTime = new Date(courseDate);

            scheduleStartTime.setHours(
                parseInt(startTimeStr.split(':')[0])+8,
                parseInt(startTimeStr.split(':')[1]),
                0
            );

            const scheduleEndTime = new Date(courseDate);
            scheduleEndTime.setHours(
                parseInt(endTimeStr.split(':')[0])+8,
                parseInt(endTimeStr.split(':')[1]),
                0
            );
            console.log(scheduleStartTime)
            const schedule = {
                id:idCounter++,
                startTime: scheduleStartTime.toISOString(), // 转换为 ISO 格式
                endTime: scheduleEndTime.toISOString(),     // 转换为 ISO 格式
                room: classroom
            };
            schedules.push(schedule);
        }
    });
    return schedules;
};

const updateCourseDateField = (value, field, index) => {
    courseDates.value[index][field] = value;
};

onMounted(() => {
    courseStore.fetchCourseSchedules();
});

import { showNotification } from '@/utils/notify'; 

</script>

<style scoped>
.calendar-preview {
    margin-top: 10px;
}

.el-slider__bar {
    transition: width 0.2s ease;
}

.el-slider__button {
    transition: left 0.2s ease;
}

.course-date-section {
    position: relative;
    padding: 10px;
    border: 1px solid #e4e7ed;
    border-radius: 4px;
    margin-bottom: 10px;
}

.course-date-section.has-top-border {
    border-top: 1px solid #e4e7ed;
}

.delete-button-wrapper {
    position: absolute;
    top: 10px;
    right: 10px;
}

.calendar-and-delete {
    margin-top: 10px;
}
</style>    